package com.qlyl.modules.information.service.impl;

import com.qlyl.common.api.vo.Result;
import com.qlyl.common.util.consumer.GsonUtil;
import com.qlyl.modules.information.service.IBannerService;
import com.qlyl.modules.information.vo.BannerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

//@Service
public class BannerServiceImpl implements IBannerService {

    private static final String BANNER_REDIS_KEY = "banners";

    @Autowired
    private RedisTemplate redisTemplate;

    public Result getBannerList(long limit) {
        Set<String> set = redisTemplate.opsForZSet().reverseRange(BANNER_REDIS_KEY, 0, limit - 1);
        List<BannerVo> lis = set.stream().map(s -> {
            return GsonUtil.current().fromJson(s, BannerVo.class);
        }).sorted(Comparator.comparing(BannerVo::getPublishDate).reversed())
        .collect(Collectors.toList());
        return Result.ok(lis);
    }


    public Result addBanner(BannerVo bannerVo) {
        String bannerJson = GsonUtil.current().toJson(bannerVo);
        double score = 1;
        Set<ZSetOperations.TypedTuple<String>> zzSet =  redisTemplate.opsForZSet().rangeWithScores(BANNER_REDIS_KEY, -1, -1);
        if (zzSet.size() == 1) {
            Iterator<ZSetOperations.TypedTuple<String>> iterator = zzSet.iterator();
            score += iterator.next().getScore();
        }
        boolean bool = redisTemplate.opsForZSet().add(BANNER_REDIS_KEY, bannerJson, score);
        if (!bool)
            return Result.error("添加Banner失败！");
        return Result.ok();
    }
}
